const jwt = require("jsonwebtoken");
const secret = "jevon-back"; //解密密钥
const sqlconfig = require("../mysql/config");
const JWT = {
  createToken: (userId, deviceIdentifier) => {
    const payload = {
      userId: userId,
      deviceIdentifier,
    };
    // time 5184000 60天
    return jwt.sign(payload, secret, { expiresIn: "1h" });
  },
  verifyToken: (req, token) => {
    return new Promise((resolve, reject) => {
      const sql = `
        SELECT user_id, ip_address, user_agent
        FROM tokens
        WHERE token = ? AND expires_at > NOW()
        LIMIT 1
      `;

      try {
        const decoded = jwt.verify(token, secret);
        sqlconfig.query(sql, [token], (error, rows) => {
          if (error) {
            console.error("Database query error:", error);
            resolve({ success: false, message: "Database error" });
            return;
          }
          if (rows.length === 0) {
            resolve({ success: false, message: "Invalid or expired token" });
            return;
          }

          const storedToken = rows[0];
          const currentIp = req.ip || req.connection.remoteAddress;
          const currentUserAgent = req.headers["user-agent"] || "";
          if (
            storedToken.ip_address !== currentIp ||
            storedToken.user_agent !== currentUserAgent
          ) {
            resolve({
              success: false,
              message: "Token does not match current device",
            });
            return;
          }

          resolve({ success: true, user: { ...decoded, ...storedToken } });
        });
      } catch (error) {
        console.error("Token verification error:", error);
        resolve({ success: false, message: "Invalid token" });
      }
    });
  },
};

module.exports = JWT;
